package com.zhangxiaofanfan.hotcode.second;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Deque;
import java.util.List;

/**
 * <a href="https://leetcode.cn/problems/rotting-oranges/?envType=study-plan-v2&envId=top-100-liked">994. 腐烂的橘子</a>
 *
 * @author zhangxiaofanfan
 * @date 2024-06-26 20:33:33
 */
public class HotCode052 {
    public static void main(String[] args) {
        // int[][] grid = {
        //         {2, 1, 1},
        //         {1, 1, 0},
        //         {1, 0, 1}
        // };
        int[][] grid = {{0,2}};
        HotCode052 hotCode = new HotCode052();
        System.out.println(hotCode.orangesRotting(grid));

    }

    public int orangesRotting(int[][] grid) {
        if (grid == null || grid.length == 0 || grid[0].length == 0) {
            return 0;
        }
        Deque<Integer> deque = new ArrayDeque<>();
        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[0].length; j++) {
                if (grid[i][j] == 2) {
                    deque.addLast(i * grid[0].length + j);
                }
            }
        }
        int minute = 0, curCount;
        while (!deque.isEmpty()) {
            curCount = deque.size();
            for (int i = 0; i < curCount; i++) {
                bfs(grid, deque);
            }
            if (deque.isEmpty()) {
                continue;
            }
            minute++;
        }

        return Arrays.stream(grid).anyMatch(row -> Arrays.stream(row).anyMatch(node -> node == 1)) ? -1 : minute;
    }

    public void bfs(int[][] grid, Deque<Integer> deque) {
        Integer first = deque.removeFirst();
        int row = first / grid[0].length, col = first % grid[0].length;
        if (row - 1 >= 0 && grid[row - 1][col] == 1) {
            grid[row - 1][col] = 2;
            deque.addLast((row - 1) * grid.length + col);
        }
        if (row + 1 < grid.length &&  grid[row + 1][col] == 1) {
            grid[row + 1][col] = 2;
            deque.addLast((row + 1) * grid.length + col);
        }
        if (col - 1 >= 0 && grid[row][col - 1] == 1) {
            grid[row][col - 1] = 2;
            deque.addLast(row * grid.length + col - 1);
        }
        if (col + 1 < grid[0].length && grid[row][col + 1] == 1) {
            grid[row][col + 1] = 2;
            deque.addLast(row * grid.length + col + 1);
        }
    }
}
